package com.beiing.tianshuai.tianshuai.huodong;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebSettings;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.app.HttpRequestConstant;
import com.beiing.tianshuai.tianshuai.base.BaseActivity;
import com.beiing.tianshuai.tianshuai.entity.UploadImgBean;
import com.beiing.tianshuai.tianshuai.freshnews.DiscoveryPreviewActivity;
import com.beiing.tianshuai.tianshuai.network.DataManager;
import com.beiing.tianshuai.tianshuai.util.DensityUtils;
import com.beiing.tianshuai.tianshuai.widget.GlideImageLoader;
import com.google.gson.Gson;
import com.tianshuai.gallerypic.config.GalleryConfig;
import com.tianshuai.gallerypic.config.GalleryPick;
import com.tianshuai.gallerypic.inter.IHandlerCallBack;
import com.zxy.tiny.Tiny;
import com.zxy.tiny.callback.FileBatchCallback;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import jp.wasabeef.richeditor.RichEditor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;

/**
 * Created by magikliu on 2017/10/22.
 */

public class HuoDongDetailEditActivity extends BaseActivity {

    private boolean isBigFontSize;
    private boolean isColorChanged;
    private static final int PERMISSIONS_REQUEST_READ_CONTACTS = 100;
    private List<String> mContentLocalPath = new ArrayList<>();
    private List<String> mContentImgPath = new ArrayList<>();
    private int resultCode = 0;

    @BindView(R.id.toolbar_iv_back)
    ImageView toolbarIvBack;
    @BindView(R.id.toolbar_tv_preview)
    TextView toolbarTvPreview;
    @BindView(R.id.toolbar_tv_publish)
    TextView toolbarTvPublish;
    @BindView(R.id.btn_font_size)
    ImageButton btnFontSize;
    @BindView(R.id.btn_font_type)
    ImageButton btnFontType;
    @BindView(R.id.btn_font_color)
    ImageButton btnFontColor;
    @BindView(R.id.btn_add_img)
    ImageButton btnAddImg;
    @BindView(R.id.rich_editor)
    RichEditor richEditor;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_huodong_edit;
    }

    @Override
    protected void init() {
        Intent intent = getIntent();
        if (!TextUtils.isEmpty(intent.getStringExtra("huodongDetail"))){

        }
        initRichEditor();
        initListener();
    }

    private void initRichEditor() {
        richEditor.setEditorFontSize(DensityUtils.sp2px(mContext, 12));
        richEditor.setEditorHeight(DensityUtils.dp2px(mContext, 300));
        richEditor.setPadding(15, 10, 15, 10);
        richEditor.setPlaceholder("添加详情内容...");
        WebSettings settings = richEditor.getSettings();
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
    }

    private void initListener() {

        toolbarIvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        //预览
        toolbarTvPreview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String content = getHtml(richEditor.getHtml());
                if (TextUtils.isEmpty(content)){
                    showShortText("还没有输入任何内容噢~");
                    return;
                }
                Intent intent = new Intent(mContext, DiscoveryPreviewActivity.class);
                intent.putExtra("content", content);
                startActivity(intent);
            }
        });

        //确认
        toolbarTvPublish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.putExtra("detail", getHtml(richEditor.getHtml()));
                HuoDongDetailEditActivity.this.setResult(resultCode, intent);
                HuoDongDetailEditActivity.this.finish();
            }
        });

        //字体大小
        btnFontSize.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isBigFontSize) {
                    richEditor.setHeading(4);
                    isBigFontSize = false;
                } else {
                    richEditor.setHeading(2);
                    isBigFontSize = true;
                }
            }
        });

        //加粗
        btnFontType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                richEditor.setBold();
            }
        });

        //字体颜色
        btnFontColor.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                richEditor.setTextColor(isColorChanged ? Color.BLACK : Color.RED);
                isColorChanged = !isColorChanged;
            }
        });

        //添加图片
        btnAddImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                selectMultiSelect();
            }
        });
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent();
        intent.putExtra("detail", getHtml(richEditor.getHtml()));
        HuoDongDetailEditActivity.this.setResult(resultCode, intent);
        HuoDongDetailEditActivity.this.finish();
    }

    // 动态权限申请
    private void checkSelfPermission() {
        if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
//            LogUtils.i("需要授权", TAG);
            if (ActivityCompat.shouldShowRequestPermissionRationale(HuoDongDetailEditActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
//                LogUtils.i("拒绝过了", TAG);
                // 提示用户如果想要正常使用，要手动去设置中授权。
                showShortText("请在 设置-应用管理 中开启此应用的储存授权。");
            } else {
//                LogUtils.i("进行授权", TAG);
                ActivityCompat.requestPermissions(HuoDongDetailEditActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSIONS_REQUEST_READ_CONTACTS);
            }
        } else {
//            LogUtils.i("不需要授权", TAG);
            // 进行正常操作
            selectMultiSelect();

        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == PERMISSIONS_REQUEST_READ_CONTACTS) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                LogUtils.i("同意授权", TAG);
                // 进行正常操作
                selectMultiSelect();

            } else {
//                LogUtils.i("拒绝授权", TAG);
            }
        }
    }

    private void selectMultiSelect() {
        List<String> path = new ArrayList<>();
        IHandlerCallBack iHandlerCallBack = new IHandlerCallBack() {
            @Override
            public void onStart() {
//                LogUtils.i("----------------- 选图开始 -----------------", TAG);
            }

            @Override
            public void onSuccess(List<String> photoList) {
                String[] filesPath = photoList.toArray(new String[photoList.size()]);
                // 压缩图片
                Tiny.FileCompressOptions tinyOptions = new Tiny.BatchFileCompressOptions();
                Tiny.getInstance().source(filesPath).batchAsFile().withOptions(tinyOptions).batchCompress(new FileBatchCallback() {
                    @Override
                    public void callback(boolean isSuccess, String[] outfile) {
                        List<String> outFiles = Arrays.asList(outfile);
                        for (int i = 0; i < outFiles.size(); i++) {
                            String s = outFiles.get(i);
//                            mEditor.insertImage(s, "content_pic");
                            mContentLocalPath.add(s);
                            uploadImg(new File(s));
                        }
                    }
                });
            }

            @Override
            public void onCancel() {
//                LogUtils.i("用户已取消", TAG);
            }

            @Override
            public void onFinish() {
//                LogUtils.i("----------------- 选图结束 -----------------", TAG);
            }

            @Override
            public void onError() {
//                LogUtils.e("----------------- 选图异常 -----------------", TAG);
            }
        };
        GalleryConfig galleryConfig = new GalleryConfig.Builder()
                .imageLoader(new GlideImageLoader())                // ImageLoader 加载框架（必填）
                .iHandlerCallBack(iHandlerCallBack)                 // 监听接口（必填）
                .provider("com.beiing.tianshuai.fileprovider")      // provider (必填)
                .pathList(path)                                     // 记录已选的图片
                .multiSelect(true)                                  // 是否多选   默认：false
                .crop(false)                                        // 快捷开启裁剪功能，仅当单选 或直接开启相机时有效
                .isShowCamera(true)                                 // 是否现实相机按钮  默认：false
                .filePath("/TianShuai/Pictures")                    // 图片存放路径
                .build();
        GalleryPick.getInstance().setGalleryConfig(galleryConfig).open(HuoDongDetailEditActivity.this);
    }

    private void uploadImg(File file) {
        RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("freshcover", file.getName(), RequestBody.create(MediaType.parse("image/*"), file))
                .build();
        DisposableObserver<ResponseBody> observer = new DisposableObserver<ResponseBody>() {
            @Override
            public void onNext(@NonNull ResponseBody body) {
//                Log.i("onNext", body.toString());
                try {
                    String result = body.string();
                    Gson gson = new Gson();
                    UploadImgBean uploadImgBean = gson.fromJson(result, UploadImgBean.class);
//                    Log.i("活动图片", uploadImgBean.getData().getFreshcover());
                    richEditor.insertImage(HttpRequestConstant.FRESH_COVER_URL + uploadImgBean.getData().getFreshcover(), "content_pic");
                    mContentImgPath.add(uploadImgBean.getData().getFreshcover());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(@NonNull Throwable e) {
//                Log.i("error", e.toString());
            }

            @Override
            public void onComplete() {

            }
        };
        DataManager.getUploadImgResult(requestBody)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }

    private String getHtml(String html) {
        html = "<html> \n" +
                "<head> \n" +
                "<style type=\\\"text/css\\\"> \n" +
                "body {font-size:15px;}\n" +
                "</style> \n" +
                "</head> \n" +
                "<body>\n" +
                "<script type='text/javascript'>\n" +
                "window.onload = function(){\n" +
                "var $img = document.getElementsByTagName('img');\n" +
                "for(var p in  $img){\n" +
                "$img[p].style.width = '100%';\n" +
                "$img[p].style.height ='auto'\n" +
                "}\n" +
                "}\n" +
                "\t\t\t\t</script>" + html + "\n" +
                "</body>\n" +
                "</html>";
        return html;
    }
}
